<template>
  <div class="monitor-status">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>监控状态</h3>
          <el-button type="primary" @click="refreshStatus">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="statusList" border style="width: 100%">
        <el-table-column prop="device_name" label="设备名称" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_update" label="最后更新时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="handleCancel(scope.row.device_name)"
            >
              取消监控
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const statusList = ref([])

const getStatusType = (status) => {
  switch (status) {
    case 'running':
      return 'success'
    case 'stopped':
      return 'danger'
    default:
      return 'info'
  }
}

const refreshStatus = async () => {
  try {
    const response = await axios.get('/api/monitor/status')
    if (response.data.status === 'success') {
      statusList.value = Object.entries(response.data.data).map(([device_name, status]) => ({
        device_name,
        ...status
      }))
    }
  } catch (error) {
    ElMessage.error('获取状态失败：' + error.message)
  }
}

const handleCancel = async (deviceName) => {
  try {
    const response = await axios.post('/api/cancel_schedule', {
      DEVICE_NAME: deviceName
    })
    
    if (response.data.status === 'success') {
      ElMessage.success('取消成功')
      refreshStatus()
    } else {
      ElMessage.error(response.data.message || '取消失败')
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
}

onMounted(() => {
  refreshStatus()
})
</script>

<style scoped>
.monitor-status {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>